import React from "react";
import ReactDOM from "react-dom";
import { ApolloProvider, ApolloClient, InMemoryCache } from "@apollo/client";
import { SubscriptionClient } from "subscriptions-transport-ws";

import { split, HttpLink } from "@apollo/client";
import { getMainDefinition } from "@apollo/client/utilities";
import { WebSocketLink } from "@apollo/client/link/ws";

import "./index.css";
import App from "./App";

const httpLink = new HttpLink({
  uri: `http://localhost:4000/graphql`,
});
const wsLink = new WebSocketLink({
  uri: `ws://localhost:4000/graphql`,
  options: {
    reconnect: true,
    timeout: 2000,
  },
});
// const wsclient = ((wsLink as any).subscriptionClient as SubscriptionClient);
// // wsclient.onDisconnected(() => {}); 处理 ws 断开后在界面上也显示断开的需求;
// wsclient.onDisconnected(() => {});
// // (wsclient as any).connect(); 处理 ws 断开后, (尽管有定时自动连接), 但用户仍有手动再次连接的需求;
// (wsclient as any).connect();
const splitLink = split(
  ({ query }) => {
    const definition = getMainDefinition(query);
    return definition.kind === "OperationDefinition" && definition.operation === "subscription";
  },
  wsLink,
  httpLink,
);

ReactDOM.render(
  <React.StrictMode>
    <ApolloProvider
      client={
        new ApolloClient({
          link: splitLink,
          cache: new InMemoryCache(),
        })
      }>
      <App />
    </ApolloProvider>
  </React.StrictMode>,
  document.getElementById("root"),
);
